package com.bfdx.testkeyevent

import android.content.Context
import android.content.Intent
import android.provider.Settings
import android.text.TextUtils
import android.view.KeyEvent
import androidx.compose.foundation.lazy.LazyListLayoutInfo
import com.orhanobut.logger.Logger

fun LazyListLayoutInfo.isNotEmpty(): Boolean {
    return this.totalItemsCount > 1
}

val LazyListLayoutInfo.lastIndex: Int
    get() = if (this.totalItemsCount > 1) this.totalItemsCount - 1 else 0

data class KeyLog(
    val action: Int,
    val keyCode: Int,
    val scanCode: Int,
    val downTime: Long,
)

fun KeyEvent.toKeyLog() = KeyLog(action = action, keyCode = keyCode, scanCode = scanCode, downTime = downTime)

fun formatKeyLog(log: KeyLog) = "键值: [${log.keyCode}], 动作: [${getActionStr(log)}]"

fun getActionStr(log: KeyLog) = when (log.action) {
    KeyEvent.ACTION_DOWN -> "↓"
    KeyEvent.ACTION_UP -> "↑"
    else -> "None"
}

fun isAccessibilityEnabled(context: Context, name: String): Boolean {
    //Logger.i("name=$name")
    val accessibilityEnabled =
        try {
            Settings.Secure.getInt(context.applicationContext.contentResolver, Settings.Secure.ACCESSIBILITY_ENABLED)
        } catch (e: Settings.SettingNotFoundException) {
            Logger.i("Error finding setting, default accessibility to not found: " + e.message)
            0
        }
    //Logger.i("ACCESSIBILITY: $accessibilityEnabled")
    val stringColonSplitter = TextUtils.SimpleStringSplitter(':')
    if (accessibilityEnabled == 1) {
        //Logger.i("***ACCESSIBILIY IS ENABLED***: ")
        val settingValue = Settings.Secure.getString(context.applicationContext.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
        //Logger.i("Setting: $settingValue")
        if (settingValue != null) {
            stringColonSplitter.setString(settingValue)
            while (stringColonSplitter.hasNext()) {
                val accessabilityService = stringColonSplitter.next()
                //Logger.i("Setting: $accessabilityService")
                if (accessabilityService.contains(name, ignoreCase = true)) {
                    //Logger.i("We've found the correct setting - accessibility is switched on!")
                    return true
                }
            }
        }
        //Logger.i("***END***")
    } else {
        //Logger.i("***ACCESSIBILIY IS DISABLED***")
    }
    return false
}

/**
 * 跳转到无障碍服务设置页面
 * @param context 设备上下文
 */
fun goToAccessibilitySetting(context: Context) {
    val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    context.startActivity(intent)
}